package com.entrogy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.*;
import com.entrogy.dao.*;
import com.entrogy.service.ParentService;
import com.entrogy.utils.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service(value="parentService")
@Transactional
public class ParentServiceImpl implements ParentService {

    private static final Logger logger = LoggerFactory.getLogger(ParentServiceImpl.class);

    @Autowired
    private ParentMapper parentMapper;//家长dao接口
    @Autowired
    private WeixinMapper weixinMapper;
    @Autowired
    private PayMapper payMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StudentMapper studentMapper;
    /**
     *  新增家长信息
     * @param parentVisitorEntity
     * @return int
     */
    @Override
    public int insertParent(ParentVisitorEntity parentVisitorEntity){
        /**
         * 操作微信表的流程： 1.根据当前操作ID 查询微信表 如果是1,3 更新电话号码 否则 根据电话号码去查询 如果存在 删除 不存在 不用管
         */
        WeixinEntity weixinEntity = weixinMapper.getWeixinByUid(parentVisitorEntity.getParentId());
        if (weixinEntity != null && weixinEntity.getUid().startsWith("3")
                || weixinEntity != null && weixinEntity.getUid().startsWith("1")) {
            weixinMapper.updateWeixinPhoneByUid(parentVisitorEntity.getParentVisitorPhone(),weixinEntity.getUid());
        } else {//删除以前访客的身份，下次进来之后就可以重新判断身份了
            weixinEntity = weixinMapper.getWeixinByPhone(parentVisitorEntity.getParentVisitorPhone());
            if (weixinEntity != null && !StrUtils.isNullOrEmpty(weixinEntity.getPhone())) {
                weixinMapper.deleteWeixinByPhone(parentVisitorEntity.getParentVisitorPhone());
            }
        }
        return parentMapper.insertParent(parentVisitorEntity);
    }

    /**
     *   修改家长信息
     * @param parentVisitorEntity
     * @return int
     */
    @Override
    public int updateParent(ParentVisitorEntity parentVisitorEntity){
        /**
         * 操作微信表的流程： 1.根据当前操作ID 查询微信表 如果是1,3 更新电话号码 否则 根据电话号码去查询 如果存在 删除 不存在 不用管
         */
        WeixinEntity weixinEntity = weixinMapper.getWeixinByUid(parentVisitorEntity.getParentId());
        if (weixinEntity != null && weixinEntity.getUid().startsWith("3")
                || weixinEntity != null && weixinEntity.getUid().startsWith("1")) {
            weixinMapper.updateWeixinPhoneByUid(parentVisitorEntity.getParentVisitorPhone(),weixinEntity.getUid());
        } else {//删除以前访客的身份，下次进来之后就可以重新判断身份了
            weixinEntity = weixinMapper.getWeixinByPhone(parentVisitorEntity.getParentVisitorPhone());
            if (weixinEntity != null && !StrUtils.isNullOrEmpty(weixinEntity.getPhone())) {
                weixinMapper.deleteWeixinByPhone(parentVisitorEntity.getParentVisitorPhone());
            }
        }
        return parentMapper.updateParent(parentVisitorEntity);
    }


    /**
     *    根据学生id  获取家长信息
     * @param map
     * @return  list
     */
    @Override
    public List<Map<String,Object>> selectParentVisitorEntityById(Map<String,Object>  map){
        return parentMapper.selectParentVisitorEntityById(map);
    }

    @Override
    public String getParentName(String uid) {
        return parentMapper.getParentName(uid);
    }

    @Override
    public Integer getSchoolCodeByParentId(String uid) {
        return parentMapper.getSchoolCodeByParentId(uid);
    }

    @Override
    public List<StudentEntity> getStudentByParentId(String pid) {
        return parentMapper.getStudentByParentId(pid);
    }

    /**
     *   根据id 获取家长对象
     * @return
     */
    @Override
    public ParentVisitorEntity getparentById(String uId) {
        return parentMapper.getparentById(uId);
    }

    @Override
    public List<StudentEntity> getStudentIsPayByPID(String uid) {
        List<StudentEntity> lists = null;
        if(uid.startsWith("1")){//教师查询本班的学生列表信息
            UserEntity userEntity = userMapper.getUserByUid(uid);//获取该用户的所在学校
            lists = userMapper.getStudentsByBanzhu(uid, userEntity.getSchoolCode());
        }else {
            lists = parentMapper.getStudentByParentId(uid);
        }
        for (StudentEntity studentEntity : lists){
            PayOrderEntity payOrderEntity = null;
            if("000".equals(studentEntity.getAllowTime())){//住校生  商品ID 1
                payOrderEntity = payMapper.getParentPayOrder(studentEntity.getId(),1);
            }else{// 走读生 商品ID 2
                payOrderEntity = payMapper.getParentPayOrder(studentEntity.getId(),2);
            }
            if(payOrderEntity != null){
                studentEntity.setIsPay(1);//1--已支付 0--未支付
                studentEntity.setPayTime(payOrderEntity.getCreateTime());//购买时间
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTime(payOrderEntity.getCreateTime());
//                calendar.add(Calendar.YEAR,1);
//                studentEntity.setExpiryDate(calendar.getTime());
                studentEntity.setExpiryDate(payOrderEntity.getExpiryDate());
            }else{
                studentEntity.setIsPay(0);
            }
        }
        return lists;
    }


    @Override
    public List<JSONObject> ListParentPhonesByStudentId(Integer studentId) {
        return parentMapper.ListParentPhonesByStudentId(studentId);
    }

    @Override
    public boolean insertParentPhoneChangeRecord(ParentInformationChangeEntity parentPhoneChangeRecord) {
        Integer row = parentMapper.insertParentPhoneChangeRecord(parentPhoneChangeRecord);
        return row == 1;
    }

    @Override
    public List<ParentVisitorEntity> listParentByStudentId(Integer studentId) {
        return parentMapper.listParentByStudentId(studentId);
    }

    @Override
    public boolean insertStudentPhoneChangeRecord(StudentInformationChangeEntity studentNewInformation) {
        return parentMapper.insertStudentPhoneChangeRecord(studentNewInformation);
    }

    @Override
    public boolean hasToAudit(String parentId, Integer flag) {
        Integer row = parentMapper.countHasToAudit(parentId, flag);
        return row == 1;
    }

    @Override
    public JSONObject getParentInformationChangeDetail(Integer changeId) {
        return parentMapper.getParentInformationChangeDetail(changeId);
    }

    @Override
    public boolean updateChangeRecord(Integer changeId, Integer agreed) {
        Integer row = parentMapper.updateChangeRecord(changeId, agreed);
        return row == 1;
    }

    @Override
    public String getNewPhone(Integer changeId) {
        return parentMapper.getNewPhone(changeId);
    }

    @Override
    public JSONObject getParentInformationChangeList(String parentId) {
        return parentMapper.getParentInformationChangeList(parentId);
    }

    @Override
    public Integer insertVerifyCode(VerifyCodeEntity verifyCodeEntity) {
        parentMapper.insertVerifyCode(verifyCodeEntity);
        return verifyCodeEntity.getId();
    }

    @Override
    public boolean compareVerifyCode(Integer id, Integer verifyCode) {
        Integer verifyCodeFormDB = parentMapper.getVerifyById(id);
        //取出该条验证码后将其状态修改为已使用
        Integer row = 0;
        if (verifyCode.equals(verifyCodeFormDB)){
            row = parentMapper.updateVerifyCodeStatus(id);
        }
        return row > 0;
    }

    @Override
    public ParentVisitorEntity getParentByPhone(String parentPhone) {
        return parentMapper.getParentByPhone(parentPhone);
    }

    @Override
    public List<ParentInformationChangeEntity> listAddParentInformation(Integer studentId) {
        return parentMapper.listAddParentInformation(studentId);
    }

    @Override
    public Integer countParent(Integer studentId) {
        JSONObject parents = parentMapper.countParent(studentId);
        int parentCount = 0;
        if (parents == null){
            return 0;
        }
        if (StringUtils.isNoneBlank(parents.getString("parent1"))){
            parentCount++;
        }
        if (StringUtils.isNoneBlank(parents.getString("parent2"))){
            parentCount++;
        }
        return parentCount;
    }

    @Override
    public JSONObject checkParentPhoneStatus(String parentPhone){
        JSONObject checkStatus = parentMapper.getParentPhoneChangeStatus(parentPhone);
        return checkStatus;
    }

    @Override
    public boolean cancelWeiXinAndPhoneBind(Integer id) {
        Integer row = parentMapper.updateWeiXinInformation(id);
        return row != null && row.equals(1);
    }

    @Override
    public boolean weiXinBindNewPhone(Integer id, String newPhone) {
        Integer row = parentMapper.updateWeiXinNewPhone(id, newPhone);
        return row != null && row.equals(1);
    }

    @Override
    public boolean deleteRepeatParent(Integer schoolCode) {
        List<ParentVisitorEntity> repeatParentList = parentMapper.listRepeatParent(schoolCode);
        int deleteTotal = 0;
        for (int i = 0; i < repeatParentList.size(); i++) {
            if (i % 2 == 0){
                ParentVisitorEntity parentVisitorEntity = repeatParentList.get(i);
                int deleteRow = parentMapper.deleteParent(parentVisitorEntity.getParentVisitorId());
                if (deleteRow > 0){
                    logger.info("当前删除家长：" + parentVisitorEntity.getParentVisitorId() + parentVisitorEntity.getParentVisitorName());
                    deleteTotal++;
                }
            }
        }
        logger.info("总计删除=》" + deleteTotal);
        return true;

    }

    @Override
    public boolean resetStudentParentPhone() {
        List<StudentEntity> studentList = studentMapper.listSchoolAllStudent(510182000, null, null, null, null, null, null);
        List<StudentEntity> initStudentList = studentMapper.listInitStudent();
        for (int i = 0; i < studentList.size(); i++) {
            StudentEntity studentEntity = studentList.get(i);
            for (int j = 0; j < initStudentList.size(); j++) {
                StudentEntity temp = initStudentList.get(j);
                if (studentEntity.getCourseId() == temp.getCourseId() && studentEntity.getGradeId() == temp.getGradeId() && studentEntity.getStudentName().equals(temp.getStudentName())){
                    String parent1Id = temp.getParent1Id();
                    String parent2Id = temp.getParent2Id();
                    studentMapper.updateStudentParent(studentEntity.getId(), parent1Id, parent2Id);
                }
            }
        }
        return false;
    }

    @Override
    public boolean updateParentWeixinInformation() {
        List<ParentVisitorEntity> parentVisitorEntityList = parentMapper.listParent(510182000);
        int total = 0;
        for (ParentVisitorEntity parentVisitorEntity : parentVisitorEntityList) {
            int row = parentMapper.updateParentWeixinInformation(parentVisitorEntity);
            if (row > 0){
                total++;
            }
        }
        logger.info("总计更新=》" + total + "人");
        return false;
    }

    @Override
    public List<ParentVisitorEntity> listClassParent(Integer schoolCode, Integer classId) {
        return parentMapper.listClassParent(schoolCode, classId);
    }

    @Override
    public List<ParentClassEntity> listClass(Integer schoolCode, Integer gradeId, Integer classId) {
        List<ParentClassEntity> parentClassList = parentMapper.listClass(schoolCode, gradeId, classId);
        // 统计每个班的家长人数
        for (ParentClassEntity entity : parentClassList) {
            Integer parent1Count = parentMapper.countClassParent(entity.getClassId(), schoolCode, 1);
            Integer parent2Count = parentMapper.countClassParent(entity.getClassId(), schoolCode, 2);
            Integer studentCount = studentMapper.countStudent(schoolCode, null, entity.getClassId(), null);
            entity.setParentCount(parent1Count + parent2Count).setStudentCount(studentCount);
        }
        return parentClassList;
    }

    @Override
    public List<StudentBasicInfoEntity> listStudentByParentId(String uid) {
        return parentMapper.listStudentByParentId(uid);
    }

    @Override
    public List<Map<String, Object>> listSchoolParent(String schoolCode, String gradeId, String classId, String name) {
        return parentMapper.listSchoolParent(schoolCode, gradeId, classId, name);
    }

    @Override
    public int countSchoolParent(String schoolCode, String gradeId, String classId, String name) {
        return parentMapper.listSchoolParent(schoolCode, gradeId, classId, name).size();
    }

    @Override
    public boolean judgeParentPayStatusByStudent(String parentVisitorId) {
        List<StudentBasicInfoEntity> studentList = parentMapper.listStudentByParentId(parentVisitorId);
        int studentPayStatus = studentMapper.countStudentPayStatus(studentList);
        return studentPayStatus > 0;
    }

    @Override
    public boolean isPayForGradeOrClass(Integer isGrade, String parentClassId, String parentVisitorId, Integer schoolCode) {
        List<StudentBasicInfoEntity> studentList = parentMapper.listStudentByParentId(parentVisitorId);
        List<StudentBasicInfoEntity> studentBelongClass = new ArrayList<>();
        Integer classOrGradeId = Integer.valueOf(parentClassId);
        for (StudentBasicInfoEntity student : studentList) {
            if (isGrade == 0){
                if (student.getClassId().equals(classOrGradeId)){
                    studentBelongClass.add(student);
                }
            }else if (isGrade == 1){
                if (student.getGradeId().equals(classOrGradeId)){
                    studentBelongClass.add(student);
                }
            }
        }
        int studentPayStatus = studentMapper.countStudentPayStatus(studentBelongClass);
        return studentPayStatus > 0;
    }

    @Override
    public String getParentIdByOpenId(String parentOpenId) {
        return parentMapper.getParentIdByOpenId(parentOpenId);
    }

    @Override
    public boolean updateParentDetail(String newParentName, String newImageUrl, String parentId) {
        int row = parentMapper.updateParentDetail(newParentName, newImageUrl, parentId);
        return row > 0;
    }

    @Override
    public JSONObject getParentStatus(String phone) {
        return parentMapper.getParentStatus(phone);
    }

    @Override
    public JSONObject getUserStatus(String phone) {
        return parentMapper.getUserStatus(phone);
    }

    @Override
    public List<ParentRegisterEntity> listParentRegisterOverView(Integer schoolCode, Integer gradeId, Integer classId) {
        return parentMapper.listParentRegisterOverView(schoolCode, gradeId, classId);
    }

    @Override
    public List<ParentRegisterStudentEntity> listParentRegisterDetail(Integer schoolCode, Integer gradeId, Integer classId) {
        return parentMapper.listParentRegisterDetail(schoolCode, gradeId, classId);
    }

    @Override
    public List<ParentStudentInfoEntity> listParentStudentInfo(Integer schoolCode, Integer gradeId, Integer classId) {
        return parentMapper.listParentStudentInfo(schoolCode, gradeId, classId);
    }

    @Override
    public ParentLoginOverviewEntity getParentLoginOverview(Integer schoolCode, Integer gradeId, Integer classId) {
        ParentLoginOverviewEntity parentLoginOverview = new ParentLoginOverviewEntity();
        // 未按学生去重
        int parentTotalCount = parentMapper.countSchoolParent(schoolCode, gradeId, classId);
        int parentLoginCount = parentMapper.countParentLogin(schoolCode, gradeId, classId);
        int parentNotLoginCount = parentTotalCount - parentLoginCount;
        double parentLoginRate = parentLoginCount / Double.valueOf(parentTotalCount);
        // 按学生去重
        int studentTotalCount = studentMapper.countStudent(schoolCode, gradeId, classId, null);
        int studentParentLoginCount = studentMapper.countStudentParentLogin(schoolCode, gradeId, classId);
        int studentParentNotLoginCount = studentTotalCount - studentParentLoginCount;
        double studentParentLoginRate = studentParentLoginCount / Double.valueOf(studentTotalCount);
        parentLoginOverview
                .setParentTotalCount(parentTotalCount)
                .setParentLoginCount(parentLoginCount)
                .setParentNotLoginCount(parentNotLoginCount)
                .setLoginRate(parentLoginRate)
                .setStudentParentLoginCount(studentParentLoginCount)
                .setStudentTotalCount(studentTotalCount)
                .setStudentParentLoginRate(studentParentLoginRate)
                .setStudentParentNotLoginCount(studentParentNotLoginCount);
        return parentLoginOverview;
    }

    @Override
    public List<ParentLoginEntity> listParentLogin(Integer schoolCode, Integer gradeId, Integer classId) {
        return parentMapper.listParentLogin(schoolCode, gradeId, classId);
    }

}
